<template>
  <van-loading type="spinner" size="20" v-if="isLoading" />
  <van-icon
    v-else
    :color="value ? '#3296fa':'#777'"
    :name="value ? 'star':'star-o'"
    @click="CollectClick"
  />
</template>
<script>
import { mapGetters } from 'vuex'
import { addCollect,deleteCollect } from '@/api/article'
  export default {
    name:'Collect',
    computed: {
      ...mapGetters(['haslogin'])
    },
    data() {
      return {
        isLoading: false // 节流阀
      }
    },
    props: {
      // 是否收藏了
      value: {
        type: Boolean,
        require:true 
      },
      // 文章ID
      articleId:{
        type:[Number,String,Object],
        require:true
      }
    },
    methods: {
      // 收藏或取消收藏
      async CollectClick() {
        if(!this.haslogin) return this.$toast.fail('登录后再收藏')
        // 1.发请求
        this.isLoading = true
        try {
          // 2. 判断行为
          if(this.value){
            //收藏了，要取消
            await deleteCollect(this.articleId)
            this.$toast.success('取消收藏成功')
          }else{
            //没收藏，要收藏
            await addCollect(this.articleId)
            this.$toast.success('收藏成功')
          }
          // 3. 更新视图
          this.$emit('input',!this.value)
        } catch (error) {
          this.$toast.fail('收藏失败')
        }
        this.isLoading = false
      }
    },
  }
</script>

<style lang="less" scoped>

</style>